package org.zjx.net.interceptor;

import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import org.zjx.log.LogLevel;
import org.zjx.log.Logger;

import java.io.IOException;

/**
 * 返回拦截器(响应拦截器)
 *
 * @author llw
 */
public class ResponseInterceptor implements Interceptor {

    private final Logger logger;  // 日志记录器

    public ResponseInterceptor() {
        this.logger = Logger.getLogger();
    }

    /**
     * 拦截
     */
    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {

        // 获取响应
        long requestTime = System.currentTimeMillis();
        Response response = chain.proceed(chain.request());

        // 获取响应体的内容
        String responseBodyString = response.body().string();

        // 记录响应数据
        logger.log("ResponseInterceptor", LogLevel.INFO, "Http response Log: " + responseBodyString);

        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), responseBodyString))
                .build();
    }
}
